// InputDlg.cpp : implementation file
//

#include "stdafx.h"
#include "EEDictionary.h"
#include "InputDlg.h"

#include "evdictbase.h"
#include "soundex.h"
#include <string.h>

// InputDlg dialog

IMPLEMENT_DYNAMIC(InputDlg, CDialog)

InputDlg::InputDlg(CWnd* pParent /*=NULL*/)
	: CDialog(InputDlg::IDD, pParent)
	, txtWord(_T(""))
	, txtPOS(_T(""))
	, txtMean(_T(""))
	, txtExample(_T(""))
	, lbMessage(_T(""))
{

}

InputDlg::~InputDlg()
{
}

void InputDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDITWORD, txtWord);
	DDX_Text(pDX, IDC_EDITWORD2, txtPOS);
	DDV_MaxChars(pDX, txtPOS, 10);
	DDV_MaxChars(pDX, txtWord, 20);
	DDX_Text(pDX, IDC_EDITWORD3, txtMean);
	DDV_MaxChars(pDX, txtMean, 100);
	DDX_Text(pDX, IDC_EDITWORD4, txtExample);
	DDV_MaxChars(pDX, txtExample, 100);
	DDX_Text(pDX, IDC_STATIC1, lbMessage);
	DDV_MaxChars(pDX, lbMessage, 100);
}


BEGIN_MESSAGE_MAP(InputDlg, CDialog)
	ON_BN_CLICKED(IDD_BUTTONSAVE, &InputDlg::OnBnClickedButtonsave)
END_MESSAGE_MAP()


// InputDlg message handlers

void InputDlg::OnBnClickedButtonsave()
{
	// TODO: Add your control notification handler code here
	char* word;
	char* hashCode;
	int address = NOT_FOUND;
	WordDefinition theWordDefinition;

	this->UpdateData(TRUE);

	if (txtWord.GetLength()==0 || txtMean.GetLength()==0 || txtPOS.GetLength()==0 || txtExample.GetLength()==0)
	{	
		lbMessage = L"Input data is incorrect! Try again";
	}
	else
	{
		strcpy_s(theWordDefinition.word, ConvertToChar(txtWord));
		strcpy_s(theWordDefinition.partOfSpeech, ConvertToChar(txtPOS));
		strcpy_s(theWordDefinition.mean, ConvertToChar(txtMean));
		strcpy_s(theWordDefinition.example, ConvertToChar(txtExample));

		word = ConvertToChar(txtWord);
		_strlwr(word);
		hashCode = soundex(word);
		address = getWordAddress(word, hashCode);

		if (address == (NOT_FOUND))
		{
			if (isBackupListEmpty())
			{
				address = writeWordToFile(theWordDefinition, DICTIONARY_DATA_FILE);
				WordIndex theWordIndex;
				strcpy_s(theWordIndex.word, word);
				strcpy_s(theWordIndex.hashCode, hashCode);
				theWordIndex.address = address;
				writeWordToFile(theWordIndex, DICTIONARY_INDEX_FILE);
			}
			else
			{
				address = getAvailableAddress();
				writeWordToFile(theWordDefinition,DICTIONARY_DATA_FILE,address);
			}
			addWordToHashTable(word, hashCode, address);
		}
		else
		{
			writeWordToFile(theWordDefinition, DICTIONARY_DATA_FILE, address);
		}
		lbMessage = L"Save data successfully!";
	}

	this->UpdateData(FALSE);
}
